//
//  JYDMView.m
//  JYDanmu
//
//  Created by jianyong.wang on 2017/12/20.
//  Copyright © 2017年 jianyong.wang. All rights reserved.
//

#import "JYDMView.h"
#import "JYTextLabel.h"
@interface JYDMView()
@property (nonatomic, assign) NSUInteger            channelCount;//显示多少行
@property (nonatomic, strong) NSMutableDictionary <NSNumber *,NSMutableArray *> * channelContainer;//每一行i作为key，每一行的内容数组作为value
@property (nonatomic, strong) NSMutableArray <NSString *> * contentContainer;//所有的数据
@property (nonatomic, assign) CGRect  currentFrame;//当前视图的frame
@property (nonatomic, strong) NSTimer  * timer;//定时器循环加载文本
@property(nonatomic, assign) float danMuHeight;//文本高度
@property(nonatomic, assign) float rollTime;//滚动时间
@end
@implementation JYDMView
/*初始化DMView*/
-(instancetype)initWithFrame:(CGRect)frame danMuHeight:(CGFloat)danMuHeight rollTime:(CGFloat)rollTime
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor redColor];
        self.currentFrame = frame;
        self.danMuHeight = danMuHeight;
        self.rollTime = rollTime;
        [self initDMChanel];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(onTimerClicked:) userInfo:nil repeats:YES];
    }
    return self;
}
- (void)onTimerClicked:(NSTimer *)timer
{
    [self insertDMQueue];
}
/* 重置Frame */
- (void)resetFrame:(CGRect)frame
{
    self.currentFrame = frame;
    [self initDMChanel];
    [self.timer invalidate];
    for (JYTextLabel * label in self.subviews) {
        [label stopAnimation];
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(onTimerClicked:) userInfo:nil repeats:YES];
}
/* 初始化DM相关参数*/
- (void)initDMChanel
{
    //计算总共可以显示多少行（航道）
    self.channelCount = floorf(self.currentFrame.size.height-10)/self.danMuHeight;
    //初始化航道
    self.channelContainer = [NSMutableDictionary dictionaryWithCapacity:self.channelCount];
    for (int i = 0; i < self.channelCount; i ++) {
        NSMutableArray * array = [NSMutableArray array];
        [self.channelContainer setObject:array forKey:@(i)];
    }
}
- (void)sendDMWithContent:(NSString *)content
{
    [self.contentContainer addObject:content];
}
/* 加入弹幕队列 */
- (void)insertDMQueue
{
    if (self.contentContainer.count == 0) return;
    //计算最佳航道
    NSUInteger bestChanel = [self dmBestChanel];
    if (bestChanel >= self.channelCount) {
        return;
    }
    // 初始化弹幕
    JYTextLabel * dmLabel = [JYTextLabel initDML:self.contentContainer.firstObject originY:bestChanel * self.danMuHeight + 5 superFrame:self.currentFrame danMuHeight:self.danMuHeight rollTime:self.rollTime];
    [self addSubview:dmLabel];
    [self.contentContainer removeObjectAtIndex:0];
    //开始动画
    __weak typeof(self) weakself = self;
    [dmLabel beginAnimationChanel:bestChanel complete:^(bool ret, NSUInteger chan) {
        [[weakself.channelContainer objectForKey:@(chan)] removeObject:dmLabel];
    }];
    //放入弹幕队列
    NSMutableArray *array = [self.channelContainer objectForKey:@(bestChanel)];
    [array addObject:dmLabel];
}
- (NSUInteger)dmBestChanel
{
    //获取DM的最佳航道
    for (int i = 0 ; i < self.channelCount ; i ++) {
        NSMutableArray * array = [self.channelContainer objectForKey:@(i)];
        JYTextLabel * dmLabel = [array lastObject];
        if (dmLabel) {
            //当上一个label从开始到现在时间*速度大于label的宽，也就是说已经完全进入整个屏幕
            NSTimeInterval duration = [[NSDate date]timeIntervalSinceDate:dmLabel.startTime];
            if (duration * dmLabel.dmlSpeed >= (dmLabel.frame.size.width + 100)) {
                return i;
            }
        }else return i;
    }
    //当上方两个条件都不满足时，1、此处做法是直接等待，不进行展示，2、另一种做法是随机给出i的值，那么就会出现重叠现象
    return 1000;
//     return arc4random_uniform((u_int32_t)channelCount);
}
-(NSMutableArray<NSString *> *)contentContainer
{
    if (_contentContainer == nil) {
        _contentContainer = [NSMutableArray array];
    }
    return  _contentContainer;
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];
    if (! newSuperview && self.timer) {
        // 销毁定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}
-(void)dealloc
{
    
}
@end
